import mongoose from 'mongoose'

// 创建房间。放置在数据库
export const creatHouse = async (ctx,next) => {
  const {openid,name,avatarUrl,gender} = ctx.query
  const creatHouse = mongoose.model('creatHouse')
  let room_num = '';
  await random_str().then(res => {
    room_num = res
  })
  const house = new creatHouse({
    house_id:room_num,
    creat_id:openid,
    name: name,
    avatarUrl:avatarUrl,
    gender:gender,
    problems_count:3,
    status:0,
    surplus_problems_count:3,
    members:{
      openid:openid,
      name: name,
      avatarUrl:avatarUrl,
      gender:gender,
      m_status:0,
      score:0,
      updatedAt:parseInt(new Date().getTime() / 1000)
    }
  })
  await house.save();
  
  ctx.body = {
    state:401,
    data:room_num
  }
  next()
}

// 刚进入房间时获取房间信息，以及更新在线信息
export const get_house_info = async (ctx,next) => {
  const time = parseInt(new Date().getTime() / 1000);
  const {house_id,openid} = ctx.query
  const creatHouse = mongoose.model('creatHouse')
  let ret = await creatHouse.findOne({house_id:house_id}).exec();
  if(!ret){
    ctx.body = {
      state:404,
      data:{}
    }
    next()
    return
  }
  ret.members.forEach((item,index)=>{
    if(item.openid === openid){
      ret.members[index].updatedAt = time;
    }
    // 清除大于10秒还未在线发送信息的成员
    if(time - item.updatedAt >= 10 ){
      ret.members.splice(index,1)
    }
    
  })
  await ret.save()
  ret = await creatHouse.findOne({house_id:house_id}).exec();
  ctx.body = {
    state:401,
    data:ret
  }
  next()
}

// 查找、成员加入房间
export const search_join_house = async (ctx,next) => {
  const time = parseInt(new Date().getTime() / 1000);
  const {openid,name,avatarUrl,gender,house_id} = ctx.query
  const creatHouse = mongoose.model('creatHouse')
  let ret = await creatHouse.findOne({house_id:house_id}).exec();
  if(!ret){
    ctx.body = {
      state:404,
      data:{}
    }
    next()
    return
  }
  let flag = true
  for(let i=0;i<ret.members.length;i++){
    if(ret.members[i].openid === openid){
      ret.members[i].updatedAt = time;
      flag = false;
      break
    }
  }
  if(flag){
    ret.members.push({
      openid:openid,
      name: name,
      avatarUrl:avatarUrl,
      gender:gender,
      m_status:0,
      score:0,
      updatedAt:time
    })
  }
  // await creatHouse.update({house_id:house_id},{members:m})
  await ret.save()
  ctx.body = {
    state:401,
    data:house_id
  }
  next()
}
export const random_str = () => {
  return new Promise(async (resolve, reject) =>{
    const creatHouse = mongoose.model('creatHouse')
    const random_arr = ['a','b','c','d','e','f','g','h','k','q'];
    const Letter = random_arr[(Math.random().toString())[2]]
    let room_num = Letter+(Math.random().toString()).substring(2,7)
    const test_ret = await creatHouse.findOne({house_id:room_num}).exec();
    if(test_ret){
      // 有重复的房号，重写
      random_str()
      return;
    }
    resolve(room_num)
  })
}

